import 'package:hive/hive.dart';
import 'package:lmmi/common/index.dart';

class TimeCapsuleService {
  static const String _boxName = 'time_capsules';

  static Future<void> initialize() async {
    if (!Hive.isAdapterRegistered(3)) {
      Hive.registerAdapter(TimeCapsuleAdapter());
    }

    await Hive.openBox<TimeCapsule>(_boxName);

    await _initializeDefaultTimeCapsules();
  }

  static Future<void> _initializeDefaultTimeCapsules() async {
    final box = Hive.box<TimeCapsule>(_boxName);

    if (box.isEmpty) {
      for (final timeCapsule in sampleTimeCapsules) {
        await box.put(timeCapsule.id, timeCapsule);
      }
    }
  }

  // 创建时间胶囊
  static Future<void> createTimeCapsule(TimeCapsule timeCapsule) async {
    final box = Hive.box<TimeCapsule>(_boxName);
    await box.put(timeCapsule.id, timeCapsule);
  }

  // 获取用户的时间胶囊
  static Future<List<TimeCapsule>> getTimeCapsulesByUserId(
    String userId,
  ) async {
    final box = Hive.box<TimeCapsule>(_boxName);
    return box.values
        .where((timeCapsule) => timeCapsule.userId == userId)
        .toList();
  }

  // 根据id获取时间胶囊
  static Future<TimeCapsule?> getTimeCapsuleById(String id) async {
    final box = Hive.box<TimeCapsule>(_boxName);
    return box.get(id);
  }

  // 更新时间胶囊
  static Future<void> updateTimeCapsule(TimeCapsule timeCapsule) async {
    final box = Hive.box<TimeCapsule>(_boxName);
    await box.put(timeCapsule.id, timeCapsule);
  }

  // 删除时间胶囊
  static Future<void> deleteTimeCapsule(String id) async {
    final box = Hive.box<TimeCapsule>(_boxName);
    await box.delete(id);
  }

  // 检测时间胶囊是否到期
  static Future<bool> isTimeCapsuleExpired(String id) async {
    final timeCapsule = await getTimeCapsuleById(id);
    if (timeCapsule == null) {
      return false;
    }
    try {
      final openDate = DateTime.parse(timeCapsule.openDate);
      return DateTime.now().isAfter(openDate);
    } catch (e) {
      // 如果日期格式无效，返回false
      return false;
    }
  }

  // 获取用户可以开启的时间胶囊
  static Future<List<TimeCapsule>> getOpenableTimeCapsulesByUserId(
    String userId,
  ) async {
    final box = Hive.box<TimeCapsule>(_boxName);
    final now = DateTime.now();

    return box.values.where((timeCapsule) {
      if (timeCapsule.userId != userId || timeCapsule.isOpen) {
        return false;
      }
      try {
        final openDate = DateTime.parse(timeCapsule.openDate);
        return now.isAfter(openDate);
      } catch (e) {
        return false;
      }
    }).toList();
  }

  // 开启时间胶囊
  static Future<void> openTimeCapsule(String id) async {
    final timeCapsule = await getTimeCapsuleById(id);
    if (timeCapsule != null) {
      final updatedCapsule = timeCapsule.copyWith(isOpen: true);
      await updateTimeCapsule(updatedCapsule);
    }
  }
}
